package org.paradise.dms.web.action.report;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.directwebremoting.annotations.RemoteProxy;
import org.paradise.dms.poi.NeoPoiUtil;
import org.paradise.dms.pojo.Apartment;
import org.paradise.dms.services.impl.JasperServiceImpl;
import org.paradise.dms.web.action.DMSBaseAction;
import org.paradise.dms.web.action.registerinfo.RegisterInfoAction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import net.sf.jasperreports.engine.JRAbstractExporter;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.export.JExcelApiExporter;

/**
 * @author
 */
@RemoteProxy(name = "jasper")
@Service
public class Jasper extends DMSBaseAction {

	private String reportname;
	private String downloadFileName;
	@Autowired
	private JasperServiceImpl jasperServiceImpl;
	private List<Apartment> aptList;
	private String apartmentname;
	private String dtype;
	
	public String getApartmentname() {
		return apartmentname;
	}

	public void setApartmentname(String apartmentname) {
		this.apartmentname = apartmentname;
	}
	
	public JasperServiceImpl getJasperServiceImpl() {
		return jasperServiceImpl;
	}

	public void setJasperServiceImpl(JasperServiceImpl jasperServiceImpl) {
		this.jasperServiceImpl = jasperServiceImpl;
	}

	public List<Apartment> getAptList() {
		return aptList;
	}

	public void setAptList(List<Apartment> aptList) {
		this.aptList = aptList;
	}

	
	//对于文件下载是必要的，与jarsper.xml中的downloadFile对应
	public InputStream getDownloadFile(){
		try{
			return ServletActionContext.getServletContext().getResourceAsStream(
					"/reports/"+reportname+".xls");
		}finally{
			//下载完毕删除生成的excel报表
			String reportPath = ServletActionContext.getRequest().getRealPath("/")
				+ "reports\\" + reportname + ".xls";
			(new   File(reportPath)).delete();   
		}
			
	}
	
	public String getDownloadFileName() {
		try {

			downloadFileName = new String(downloadFileName.getBytes(), "ISO8859-1");

			} catch (UnsupportedEncodingException e) {

			e.printStackTrace();

			}
		return downloadFileName;
	}


	public void setDownloadFileName(String downloadFileName) {
		this.downloadFileName = downloadFileName+".xls";
	}

	
	private static Logger log = Logger.getLogger(Jasper.class);
	public String getReportname() {
		return reportname;
	}

	
	public void setReportname(String reportname) {
		this.reportname = reportname;
	}

	public String getReport() {
		log.info(this.getReportname()+"==============");
		fetchReport(this.getReportname());
		//outputFile(this.getReportname());
		
		
		return SUCCESS;
	}

	public String fetchReport(String reportname) {
		
		String reportPath = ServletActionContext.getRequest().getRealPath("/")
		+ "reports\\" + reportname + ".xls";
		
		String jasperFilePath = ServletActionContext.getRequest().getRealPath(
				"/")
				+ "reports\\" + reportname + ".jasper";
		
		File reportFile = new File(jasperFilePath);
		// System.out.println(ServletActionContext.getRequest()
		// .getRealPath("/")
		// + "reports\\"+reportname+".jasper");
		Connection conn = null;

		String driver = "com.mysql.jdbc.Driver";
		String strUrl = "jdbc:mysql://localhost:3306/dms";

		try {
			Class.forName(driver);
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			conn = DriverManager.getConnection(strUrl, "root", "udbvj");
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		Map parameter = new HashMap();
		if(null != this.getApartmentname()){
			parameter.put("apmname", this.getApartmentname());
		}
		if(null != this.getDtype()){
			parameter.put("dormtype", this.getDtype());
			System.out.print(this.getDtype()+"---------------");
		}

		JasperPrint jasperPrint = null;
		try {
			jasperPrint = JasperFillManager.fillReport(reportFile.getPath(),
					parameter, conn);
		} catch (JRException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		JRAbstractExporter exporter = new JExcelApiExporter();
		FileOutputStream output = null;

		try {
			output = new FileOutputStream(reportPath);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
		exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, output);
		
		try {
			exporter.exportReport();
		} catch (JRException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			output.close();
			conn.close();
			//删除已经存在的名为reportname的excel文件
			File reportExcel = new File(reportPath);
			reportExcel.deleteOnExit();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return SUCCESS;
	}
	/**
	 * 
	 * Description: 列出所有的公寓，在按公寓名选择统计的报表中用到
	 * @Version1.0 Aug 6, 2009 9:20:38 AM 郑旭（zhengxu2006@gmail.com）创建
	 * @return
	 */
	public String findApartments(){
		aptList = jasperServiceImpl.listAllApartment();
		this.getRequest().setAttribute("aptList", aptList);
		return SUCCESS;
	}

	public String getDtype() {
		return dtype;
	}

	public void setDtype(String dtype) {
		this.dtype = dtype;
	}






	


}